package com.zshan.clinic.admin.service.stock;

import com.zshan.clinic.admin.entity.dto.StockOrderPurchaseDTO;
import com.zshan.clinic.admin.entity.dto.StockOrderReqDTO;
import com.zshan.clinic.admin.entity.medical.emp.ClinicEmpSimple;
import com.zshan.clinic.admin.entity.medical.stock.DrugOut;
import com.zshan.clinic.admin.entity.medical.stock.StockOutDTO;
import com.zshan.clinic.admin.entity.vo.*;
import com.zshan.clinic.admin.mapper.stock.SpecStockOrderMapper;
import com.zshan.clinic.admin.service.clinic.ClinicEmpService;
import com.zshan.clinic.common.constant.CommonConstant;
import com.zshan.clinic.common.enums.*;
import com.zshan.clinic.common.exception.BusinessFailException;
import com.zshan.clinic.common.util.page.PageInfo;
import com.zshan.clinic.common.util.page.PageUtils;
import com.zshan.clinic.common.util.string.StringUtil;
import com.zshan.clinic.common.util.uuid.IdBuilder;
import com.zshan.clinic.database.dao.*;
import com.zshan.clinic.database.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 药库订单
 */
@Slf4j
@Service
public class StockOrderService {

    /**
     * 采购订单
     */
    @Autowired
    private StockOrderPurchaseMapper stockOrderPurchaseMapper;

    @Autowired
    private StockOrderPurchaseDetailMapper stockOrderPurchaseDetailMapper;

    @Autowired
    private SpecStockOrderMapper specStockOrderMapper;

    @Autowired
    private ClinicEmpService clinicEmpService;

    @Autowired
    private StockSupplyService stockSupplyService;

    @Autowired
    private DrugProfileService drugProfileService;

    @Autowired
    private StockDrugService stockDrugService;

    @Autowired
    private StockOrderLogMapper stockOrderLogMapper;

    /**
     * 领用单
     */
    @Autowired
    private StockOrderReqMapper stockOrderReqMapper;

    @Autowired
    private StockOrderReqDetailMapper stockOrderReqDetailMapper;

    @Autowired
    private StockOrderTransferMapper stockOrderTransferMapper;

    @Autowired
    private StockOrderTransferDetailMapper stockOrderTransferDetailMapper;


    /**
     * 审核领用单
     * @param orderReq
     */
    @Transactional(rollbackFor = Exception.class)
    public void reviewReq(StockOrderReq orderReq) {
        if(!ReqOrderStatusEnum.isReview(orderReq.getOrderStatus())){
            throw new BusinessFailException("审核状态错误");
        }
        if(ReqOrderStatusEnum.RETURNED.getValue().equals(orderReq.getOrderStatus())){
            if(StringUtil.isBlank(orderReq.getRefuseReason())){
                throw new BusinessFailException("请添加拒绝原因！");
            }
        }
        StockOrderReq dbStockOrderReq = getReqById(orderReq.getOrderId());
        if (dbStockOrderReq == null) {
            throw new BusinessFailException("领用订单不存在");
        }
        if(!ReqOrderStatusEnum.PENDING.getValue().equals(dbStockOrderReq.getOrderStatus())){
            throw new BusinessFailException("订单状态不允许");
        }
        dbStockOrderReq.setAuditUserId(orderReq.getAuditUserId());
        dbStockOrderReq.setAuditUserName(orderReq.getAuditUserName());
        dbStockOrderReq.setAuditTime(new Date());
        dbStockOrderReq.setOrderStatus(orderReq.getOrderStatus());
        dbStockOrderReq.setRefuseReason(orderReq.getRefuseReason());
        dbStockOrderReq.setUpdateUserId(orderReq.getAuditUserId());
        dbStockOrderReq.setUpdateBy(orderReq.getAuditUserName());
        dbStockOrderReq.setUpdateTime(new Date());
        stockOrderReqMapper.updateByPrimaryKeySelective(dbStockOrderReq);
        //TODO 保存日志 可以改为异步
        String logType = StockLogTypeEnum.REQ_PASS.getValue();
        if(ReqOrderStatusEnum.RETURNED.getValue().equals(orderReq.getOrderStatus())){
            logType = StockLogTypeEnum.REQ_REFUSE.getValue();
        }
        addOrderLog(dbStockOrderReq.getClinicId(),
                dbStockOrderReq.getOrderId(),
                StockOrderTypeEnum.DISTRIBUTION.getValue(),
                logType,
                dbStockOrderReq.getAuditUserId(),
                dbStockOrderReq.getAuditUserName(),
                dbStockOrderReq.getRefuseReason());
        if(ReqOrderStatusEnum.RETURNED.getValue().equals(orderReq.getOrderStatus())){
            return;
        }
        //执行出库操作
        StockOutDTO stockOutDTO = new StockOutDTO();
        stockOutDTO.setTransType(DrugTransTypeEnum.REQ.getValue());
        stockOutDTO.setOrderId(dbStockOrderReq.getOrderId());
        stockOutDTO.setOutUserId(dbStockOrderReq.getAuditUserId());
        stockOutDTO.setOutUserBy(dbStockOrderReq.getAuditUserName());
        stockOutDTO.setDrugOutList(getDrugOutList(dbStockOrderReq.getClinicId(),dbStockOrderReq.getOrderId()));
        stockDrugService.stockOut(stockOutDTO);
    }

    public List<DrugOut> getDrugOutList(Long clinicId,Long orderId) {
        StockOrderReqVo stockOrderReqVo = getOrderReqDetail(clinicId,orderId);
        List<StockOrderReqDetailVo> detailVoList = stockOrderReqVo.getDetailList();
        Map<String, DrugOut> merged = new LinkedHashMap<>();
        for (StockOrderReqDetailVo d : detailVoList) {
            String key = d.getDrugId() + "-" + stockOrderReqVo.getStorageId();
            merged.compute(key, (k, acc) -> {
                if (acc == null) {
                    // 复制一份，避免直接修改原对象（可选）
                    DrugOut x = new DrugOut();
                    x.setDrugId(d.getDrugId());
                    x.setDrugName(d.getDrugName());
                    x.setStorageId(stockOrderReqVo.getStorageId());
                    x.setMinPackQty(d.getMinPackQty());     // 一般是规格，不累加
                    x.setStockQty(d.getOrderQty());
                    x.setMinStockQty(CommonConstant.DEFAULT_0);
                    return x;
                }
                acc.setStockQty(acc.getStockQty() + d.getOrderQty());
                return acc;
            });
        }
        return new ArrayList<>(merged.values());
    }

    /**
     * 查询领用单列表
     * @param clinicId
     * @param orderNo
     * @param orderStatus
     * @param deptId
     * @param storageId
     * @param pageNo
     * @param pageSize
     * @return
     */
    public PageInfo<StockOrderReqPageVo> getOrderReqList(Long clinicId, String orderNo, String orderStatus, Long deptId, Long storageId, Integer pageNo, Integer pageSize){
        Long totalCount = specStockOrderMapper.getOrderReqCount(clinicId,orderNo,orderStatus,deptId,storageId);
        if(StringUtil.isBlank(totalCount)){
            return PageInfo.build();
        }
        List<StockOrderReqPageVo> orderList = specStockOrderMapper.getOrderReqList(clinicId,orderNo,orderStatus,deptId,storageId,PageUtils.getOffset(pageNo,pageSize),pageSize);
        return new PageInfo<>(totalCount,orderList);
    }

    /**
     * 查询领用单详情
     * @param clinicId
     * @param orderId
     * @return
     */
    public StockOrderReqVo getOrderReqDetail(Long clinicId, Long orderId){
        return specStockOrderMapper.getOrderReqDetail(clinicId,orderId);
    }


    /**
     * 创建领用单
     * @param stockOrderReqDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void addReqDTO(StockOrderReqDTO stockOrderReqDTO) {
        validateStockOrderReqDTO(stockOrderReqDTO);
        stockOrderReqDTO.setInTime(new Date());
        stockOrderReqDTO.setOrderNo(IdBuilder.getUniqueId("LY"));
        stockOrderReqDTO.setOrderStatus(ReqOrderStatusEnum.PENDING.getValue());
        stockOrderReqDTO.setIsEnabled(YesOrNoEnum.YES.getValue());
        stockOrderReqDTO.setIsDelete(YesOrNoEnum.NO.getValue());
        stockOrderReqDTO.setCreateTime(new Date());
        stockOrderReqMapper.insertSelective(stockOrderReqDTO);
        //批量添加明细
        addReqDetailsBatch(
                stockOrderReqDTO.getClinicId(),
                stockOrderReqDTO.getOrderId(),
                stockOrderReqDTO.getCreateUserId(),
                stockOrderReqDTO.getCreateBy(),
                stockOrderReqDTO.getDetailList());
        //保存日志
        addOrderLog(stockOrderReqDTO.getClinicId(),stockOrderReqDTO.getOrderId(),
                StockOrderTypeEnum.DISTRIBUTION.getValue(),
                StockLogTypeEnum.DRAFT.getValue(),
                stockOrderReqDTO.getCreateUserId(),
                stockOrderReqDTO.getCreateBy(),null);
    }

    /**
     * 批量添加领用明细
     * @param clinicId
     * @param orderId
     * @param createUserId
     * @param createBy
     * @param detailList
     */
    public void addReqDetailsBatch(Long clinicId, Long orderId, Long createUserId, String createBy, List<StockOrderReqDetail> detailList) {
        Date createTime = new Date();
        for(StockOrderReqDetail stockOrderReqDetail : detailList){
            stockOrderReqDetail.setOrderId(orderId);
            stockOrderReqDetail.setClinicId(clinicId);
            stockOrderReqDetail.setIsEnabled(YesOrNoEnum.YES.getValue());
            stockOrderReqDetail.setIsDelete(YesOrNoEnum.NO.getValue());
            stockOrderReqDetail.setCreateUserId(createUserId);
            stockOrderReqDetail.setCreateBy(createBy);
            stockOrderReqDetail.setCreateTime(createTime);
        }
        specStockOrderMapper.addReqDetailsBatch(detailList);
    }


    public void validateStockOrderReqDTO(StockOrderReqDTO stockOrderReqDTO) {
        List<StockOrderReqDetail> detailList = stockOrderReqDTO.getDetailList();
        if(CollectionUtils.isEmpty(detailList)){
            throw new BusinessFailException("请添加产品信息");
        }
        ClinicEmpSimple clinicEmp = clinicEmpService.getEmpSimple(stockOrderReqDTO.getClinicId(),stockOrderReqDTO.getReqUserId());
        if(clinicEmp == null){
            throw new BusinessFailException("领用人不存在");
        }
        stockOrderReqDTO.setReqUserName(clinicEmp.getEmpName());
        stockOrderReqDTO.setReqDeptId(clinicEmp.getDeptId());
        stockOrderReqDTO.setReqDeptName(clinicEmp.getDeptName());
        StockStorage stockStorage = stockSupplyService.getEnableStockStorageById(stockOrderReqDTO.getStorageId());
        if(stockStorage == null){
            throw new BusinessFailException("药库不存在");
        }
        Integer drugKindCount = CommonConstant.DEFAULT_0;
        Integer totalQty = CommonConstant.DEFAULT_0;
        for(StockOrderReqDetail stockOrderReqDetail : detailList){
            StockDrugProfile drugProfile = drugProfileService.getProfileById(stockOrderReqDetail.getDrugId());
            if(drugProfile == null){
                throw new BusinessFailException("请先给药品建档！");
            }
            if(stockOrderReqDetail.getOrderQty() == null || stockOrderReqDetail.getOrderQty() <= CommonConstant.DEFAULT_0){
                throw new BusinessFailException("领用数量必须大于"+CommonConstant.DEFAULT_0);
            }
            totalQty = totalQty + stockOrderReqDetail.getOrderQty();
            drugKindCount = drugKindCount + CommonConstant.DEFAULT_1;
        }
        stockOrderReqDTO.setDrugKindCount(drugKindCount);
        stockOrderReqDTO.setTotalQty(totalQty);
    }


    /**
     * 查询仓库订单变动流水列表
     * @param clinicId
     * @param orderId
     * @param orderType
     * @param pageNo
     * @param pageSize
     * @return
     */
    public PageInfo<StockOrderLogVo> getOrderLogList(Long clinicId,Long orderId, String orderType,Integer pageNo, Integer pageSize) {
        PageInfo<StockOrderLog> pageInfo = getLogListByCondition(clinicId,orderId,orderType,pageNo,pageSize);
        if(pageInfo.getTotalCount() <= CommonConstant.DEFAULT_0){
            return PageInfo.build();
        }
        List<StockOrderLog> logList = pageInfo.getList();
        // 将实体列表转换为DTO列表
        return new PageInfo<>(pageInfo.getTotalCount(),logList.stream().map(stockOrderLog -> {
            StockOrderLogVo stockOrderLogVo = new StockOrderLogVo();
            BeanUtils.copyProperties(stockOrderLog, stockOrderLogVo);
            return stockOrderLogVo;
        }).collect(Collectors.toList()));
    }

    /**
     * 采购订单
     * @param orderNo
     * @param orderStatus
     * @param settleStatus
     * @param storageId
     * @param pageNo
     * @param pageSize
     * @return
     */
    public PageInfo<StockOrderPurchasePageVo> getOrderPurchaseList(Long clinicId,String orderNo, String orderStatus, String settleStatus, Long storageId, Integer pageNo, Integer pageSize){
        Long totalCount = specStockOrderMapper.getOrderPurchaseCount(clinicId,orderNo,orderStatus,settleStatus,storageId);
        if(StringUtil.isBlank(totalCount)){
            return PageInfo.build();
        }
        List<StockOrderPurchasePageVo> orderList = listOrderPurchase(clinicId,orderNo,orderStatus,settleStatus,storageId,pageNo,pageSize);
        return new PageInfo<>(totalCount,orderList);
    }

    public List<StockOrderPurchasePageVo> listOrderPurchase(Long clinicId,String orderNo, String orderStatus, String settleStatus, Long storageId, Integer pageNo, Integer pageSize){
        List<StockOrderPurchasePageVo> orderList = specStockOrderMapper.getOrderPurchaseList(clinicId,orderNo,orderStatus,settleStatus,storageId,PageUtils.getOffset(pageNo,pageSize),pageSize);
        return orderList;
    }

    /**
     * 查询采购单详情
     * @param clinicId
     * @param orderId
     * @return
     */
    public StockOrderPurchaseVo getOrderPurchaseDetail(Long clinicId,Long orderId){
        return specStockOrderMapper.getOrderPurchaseDetail(clinicId,orderId);
    }

    /**
     * 插入采购单明细
     * @param clinicId
     * @param orderId
     * @return
     */
    public StockOrderPurchaseDTO getStockOrderPurchaseDTO(Long clinicId,Long orderId){
        return specStockOrderMapper.getStockOrderPurchaseDTO(clinicId,orderId);
    }

    /**
     * 新增采购单
     * @param stockOrderPurchaseDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void addPurchaseDTO(StockOrderPurchaseDTO stockOrderPurchaseDTO) {
        validateStockOrderPurchaseDTO(stockOrderPurchaseDTO);
        stockOrderPurchaseDTO.setInTime(new Date());
        stockOrderPurchaseDTO.setOrderNo(IdBuilder.getUniqueId("P"));
        stockOrderPurchaseDTO.setOrderStatus(PurchaseOrderStatusEnum.PENDING_APPROVAL.getValue());
        stockOrderPurchaseDTO.setSettleStatus(SettleStatusEnum.PENDING_SETTLEMENT.getValue());
        stockOrderPurchaseDTO.setIsEnabled(YesOrNoEnum.YES.getValue());
        stockOrderPurchaseDTO.setIsDelete(YesOrNoEnum.NO.getValue());
        stockOrderPurchaseDTO.setCreateTime(new Date());
        stockOrderPurchaseMapper.insertSelective(stockOrderPurchaseDTO);
        //批量添加明细
        addPurchaseDetailsBatch(
                stockOrderPurchaseDTO.getClinicId(),
                stockOrderPurchaseDTO.getOrderId(),
                stockOrderPurchaseDTO.getCreateUserId(),
                stockOrderPurchaseDTO.getCreateBy(),
                stockOrderPurchaseDTO.getDetailList());
        //保存日志
        addOrderLog(stockOrderPurchaseDTO.getClinicId(),
                stockOrderPurchaseDTO.getOrderId(),
                StockOrderTypeEnum.PURCHASE.getValue(),
                StockLogTypeEnum.DRAFT.getValue(),
                stockOrderPurchaseDTO.getCreateUserId(),
                stockOrderPurchaseDTO.getCreateBy(),null);
    }

    /**
     * 批量添加采购明细
     * @param clinicId
     * @param orderId
     * @param createUserId
     * @param createBy
     * @param detailList
     */
    @Transactional(rollbackFor = Exception.class)
    public void addPurchaseDetailsBatch(Long clinicId, Long orderId, Long createUserId, String createBy, List<StockOrderPurchaseDetail> detailList) {
        Date createTime = new Date();
        for(StockOrderPurchaseDetail stockOrderPurchaseDetail : detailList){
            stockOrderPurchaseDetail.setOrderId(orderId);
            stockOrderPurchaseDetail.setClinicId(clinicId);
            stockOrderPurchaseDetail.setIsEnabled(YesOrNoEnum.YES.getValue());
            stockOrderPurchaseDetail.setIsDelete(YesOrNoEnum.NO.getValue());
            stockOrderPurchaseDetail.setCreateUserId(createUserId);
            stockOrderPurchaseDetail.setCreateBy(createBy);
            stockOrderPurchaseDetail.setCreateTime(createTime);
        }
        specStockOrderMapper.addPurchaseDetailsBatch(detailList);
    }

    /**
     * 采购订单
     * @param stockOrderPurchaseDTO
     */
    public void validateStockOrderPurchaseDTO(StockOrderPurchaseDTO stockOrderPurchaseDTO) {
        List<StockOrderPurchaseDetail> detailList = stockOrderPurchaseDTO.getDetailList();
        if(CollectionUtils.isEmpty(detailList)){
            throw new BusinessFailException("请添加产品信息");
        }
        ClinicEmp clinicEmp = clinicEmpService.getEnabledEmpById(stockOrderPurchaseDTO.getInUserId());
        if(clinicEmp == null){
            throw new BusinessFailException("制单人不存在");
        }
        stockOrderPurchaseDTO.setInUserName(clinicEmp.getEmpName());
        StockStorage stockStorage = stockSupplyService.getEnableStockStorageById(stockOrderPurchaseDTO.getStorageId());
        if(stockStorage == null){
            throw new BusinessFailException("药库不存在");
        }
        StockSupply stockSupply = stockSupplyService.getEnableSupplyById(stockOrderPurchaseDTO.getSupplyId());
        if(stockSupply == null){
            throw new BusinessFailException("供应商不存在");
        }
        int drugKindCount = CommonConstant.DEFAULT_0;
        int totalQty = CommonConstant.DEFAULT_0;
        int totalAmount = CommonConstant.DEFAULT_0;
        for(StockOrderPurchaseDetail stockOrderPurchaseDetail : detailList){
            StockDrugProfile drugProfile = drugProfileService.getProfileById(stockOrderPurchaseDetail.getDrugId());
            if(drugProfile == null){
                throw new BusinessFailException("请先给药品建档！");
            }
            int orderQty = stockOrderPurchaseDetail.getOrderQty();
            if(orderQty <= CommonConstant.DEFAULT_0){
                throw new BusinessFailException("采购数量必须大于"+CommonConstant.DEFAULT_0);
            }
            int price = stockOrderPurchaseDetail.getPrice();
            if(price <= CommonConstant.DEFAULT_0){
                throw new BusinessFailException("价格必须大于"+CommonConstant.DEFAULT_0);
            }
            if(StringUtil.isBlank(stockOrderPurchaseDetail.getBatchNo())){
                throw new BusinessFailException("生产批号不能为空");
            }
            if(stockOrderPurchaseDetail.getBatchDate() == null){
                throw new BusinessFailException("生产日期不能为空");
            }
            if(stockOrderPurchaseDetail.getExpiryDate() == null){
                throw new BusinessFailException("有效日期不能为空");
            }
            stockOrderPurchaseDetail.setOrderUnit(drugProfile.getPackUnit());
            stockOrderPurchaseDetail.setMinOrderQty(CommonConstant.DEFAULT_0);
            stockOrderPurchaseDetail.setMinOrderUnit(drugProfile.getMinPackUnit());
            stockOrderPurchaseDetail.setSubtotal(orderQty * price);
            drugKindCount = drugKindCount + CommonConstant.DEFAULT_1;
            totalQty = totalQty + orderQty;
            totalAmount = totalAmount + stockOrderPurchaseDetail.getSubtotal();
        }
        stockOrderPurchaseDTO.setDrugKindCount(drugKindCount);
        stockOrderPurchaseDTO.setTotalQty(totalQty);
        stockOrderPurchaseDTO.setTotalAmount(totalAmount);
    }


    /**
     * 退款
     * @param stockOrderPurchase
     */
    @Transactional(rollbackFor = Exception.class)
    public void refusePurchase(StockOrderPurchase stockOrderPurchase) {
        if(StringUtil.isBlank(stockOrderPurchase.getSettleRemark())){
            throw new BusinessFailException("请填写退款备注！");
        }
        StockOrderPurchase dbStockOrderPurchase = getPurchaseById(stockOrderPurchase.getOrderId());
        if (dbStockOrderPurchase == null) {
            throw new BusinessFailException("订单不存在");
        }
        if(!SettleStatusEnum.SETTLED.getValue().equals(dbStockOrderPurchase.getSettleStatus())){
            throw new BusinessFailException("订单状态不允许");
        }
        dbStockOrderPurchase.setSettleUserId(stockOrderPurchase.getSettleUserId());
        dbStockOrderPurchase.setSettleUserName(stockOrderPurchase.getSettleUserName());
        dbStockOrderPurchase.setSettleTime(new Date());
        dbStockOrderPurchase.setSettleStatus(SettleStatusEnum.REFUNDED.getValue());
        dbStockOrderPurchase.setSettleRemark(stockOrderPurchase.getSettleRemark());
        dbStockOrderPurchase.setUpdateUserId(stockOrderPurchase.getSettleUserId());
        dbStockOrderPurchase.setUpdateBy(stockOrderPurchase.getSettleUserName());
        dbStockOrderPurchase.setUpdateTime(new Date());
        stockOrderPurchaseMapper.updateByPrimaryKeySelective(dbStockOrderPurchase);
        //保存日志
        addOrderLog(stockOrderPurchase.getClinicId(),stockOrderPurchase.getOrderId(),
                StockOrderTypeEnum.PURCHASE.getValue(),
                StockLogTypeEnum.REFUNDED.getValue(),
                stockOrderPurchase.getSettleUserId(),
                stockOrderPurchase.getSettleUserName(),stockOrderPurchase.getSettleRemark());
    }


    /**
     * 结算订单
     * @param stockOrderPurchase
     */
    @Transactional(rollbackFor = Exception.class)
    public void settlePurchase(StockOrderPurchase stockOrderPurchase) {
        StockOrderPurchase dbStockOrderPurchase = getPurchaseById(stockOrderPurchase.getOrderId());
        if (dbStockOrderPurchase == null) {
            throw new BusinessFailException("订单不存在");
        }
        if(!SettleStatusEnum.PENDING_SETTLEMENT.getValue().equals(dbStockOrderPurchase.getSettleStatus())){
            throw new BusinessFailException("订单状态不允许");
        }
        dbStockOrderPurchase.setSettleUserId(stockOrderPurchase.getSettleUserId());
        dbStockOrderPurchase.setSettleUserName(stockOrderPurchase.getSettleUserName());
        dbStockOrderPurchase.setSettleTime(new Date());
        dbStockOrderPurchase.setSettleStatus(SettleStatusEnum.SETTLED.getValue());
        dbStockOrderPurchase.setSettleRemark(stockOrderPurchase.getSettleRemark());
        dbStockOrderPurchase.setUpdateUserId(stockOrderPurchase.getSettleUserId());
        dbStockOrderPurchase.setUpdateBy(stockOrderPurchase.getSettleUserName());
        dbStockOrderPurchase.setUpdateTime(new Date());
        stockOrderPurchaseMapper.updateByPrimaryKeySelective(dbStockOrderPurchase);
        //保存日志
        addOrderLog(stockOrderPurchase.getClinicId(),stockOrderPurchase.getOrderId(),
                StockOrderTypeEnum.PURCHASE.getValue(),
                StockLogTypeEnum.SETTLED.getValue(),
                stockOrderPurchase.getSettleUserId(),
                stockOrderPurchase.getSettleUserName(),stockOrderPurchase.getSettleRemark());
    }


    /**
     * 审核采购单
     * @param stockOrderPurchase
     */
    @Transactional(rollbackFor = Exception.class)
    public void reviewPurchase(StockOrderPurchase stockOrderPurchase) {
        if(!PurchaseOrderStatusEnum.isReview(stockOrderPurchase.getOrderStatus())){
            throw new BusinessFailException("审核状态错误");
        }
        if(PurchaseOrderStatusEnum.RETURNED.getValue().equals(stockOrderPurchase.getOrderStatus())){
            if(StringUtil.isBlank(stockOrderPurchase.getRefuseReason())){
                throw new BusinessFailException("请填写拒绝原因");
            }
        }
        StockOrderPurchase dbStockOrderPurchase = getPurchaseById(stockOrderPurchase.getOrderId());
        if (dbStockOrderPurchase == null) {
            throw new BusinessFailException("采购订单不存在");
        }
        if(!PurchaseOrderStatusEnum.PENDING_APPROVAL.getValue().equals(dbStockOrderPurchase.getOrderStatus())){
            throw new BusinessFailException("订单状态不允许");
        }
        dbStockOrderPurchase.setAuditUserId(stockOrderPurchase.getAuditUserId());
        dbStockOrderPurchase.setAuditUserName(stockOrderPurchase.getAuditUserName());
        dbStockOrderPurchase.setAuditTime(new Date());
        dbStockOrderPurchase.setOrderStatus(stockOrderPurchase.getOrderStatus());
        dbStockOrderPurchase.setRefuseReason(stockOrderPurchase.getRefuseReason());
        dbStockOrderPurchase.setUpdateUserId(stockOrderPurchase.getAuditUserId());
        dbStockOrderPurchase.setUpdateBy(stockOrderPurchase.getAuditUserName());
        dbStockOrderPurchase.setUpdateTime(new Date());
        stockOrderPurchaseMapper.updateByPrimaryKeySelective(dbStockOrderPurchase);
        //保存日志
        String logType = StockLogTypeEnum.INBOUND.getValue();
        if(PurchaseOrderStatusEnum.RETURNED.getValue().equals(stockOrderPurchase.getOrderStatus())){
            logType = StockLogTypeEnum.RETURNED.getValue();
        }
        addOrderLog(stockOrderPurchase.getClinicId(),
                stockOrderPurchase.getOrderId(),
                StockOrderTypeEnum.PURCHASE.getValue(),
                logType,
                stockOrderPurchase.getAuditUserId(),
                stockOrderPurchase.getAuditUserName(),dbStockOrderPurchase.getRefuseReason());
        if(!PurchaseOrderStatusEnum.isPass(stockOrderPurchase.getOrderStatus())){
            return;
        }
        //执行入库操作
        stockDrugService.stockIn(getStockOrderPurchaseDTO(stockOrderPurchase.getClinicId(),stockOrderPurchase.getOrderId()));
    }


    /**
     * 根据条件分页查询采购订单列表
     * @param orderNo 订单号
     * @param pageNo 页码
     * @param pageSize 每页大小
     * @return
     */
    public List<StockOrderPurchase> getStockOrderPurchaseListByParams(String orderNo, Integer pageNo, Integer pageSize) {
        StockOrderPurchaseExample example = new StockOrderPurchaseExample();
        StockOrderPurchaseExample.Criteria criteria = example.createCriteria();
        if (StringUtil.isNotBlank(orderNo)) {
            criteria.andOrderNoLike("%" + orderNo + "%");
        }
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        example.setOffset(PageUtils.getOffset(pageNo, pageSize));
        example.setLimit(pageSize);
        return stockOrderPurchaseMapper.selectByExample(example);
    }

    /**
     * 添加采购订单
     * @param stockOrderPurchase
     */
    @Transactional(rollbackFor = Exception.class)
    public void addPurchase(StockOrderPurchase stockOrderPurchase) {
        validateStockOrderPurchase(stockOrderPurchase);
        stockOrderPurchase.setIsDelete(YesOrNoEnum.NO.getValue());
        stockOrderPurchase.setIsEnabled(YesOrNoEnum.YES.getValue());
        stockOrderPurchase.setCreateTime(new Date());
        stockOrderPurchaseMapper.insertSelective(stockOrderPurchase);
    }

    /**
     * 校验采购订单实体
     * @param stockOrderPurchase
     */
    public void validateStockOrderPurchase(StockOrderPurchase stockOrderPurchase) {
        if (StringUtil.isBlank(stockOrderPurchase.getOrderNo())) {
            throw new BusinessFailException("订单号不能为空");
        }
    }

    /**
     * 根据ID查询采购订单
     * @param orderId
     * @return
     */
    public StockOrderPurchase getPurchaseById(Long orderId) {
        if (orderId == null) {
            return null;
        }
        StockOrderPurchase stockOrderPurchase = stockOrderPurchaseMapper.selectByPrimaryKey(orderId);
        if (stockOrderPurchase == null || YesOrNoEnum.YES.getValue().equals(stockOrderPurchase.getIsDelete())) {
            return null;
        }
        return stockOrderPurchase;
    }

    /**
     * 修改采购订单
     * @param stockOrderPurchase
     */
    @Transactional(rollbackFor = Exception.class)
    public void updatePurchase(StockOrderPurchase stockOrderPurchase) {
        validateStockOrderPurchase(stockOrderPurchase);
        StockOrderPurchase dbStockOrderPurchase = getPurchaseById(stockOrderPurchase.getOrderId());
        if (dbStockOrderPurchase == null) {
            throw new BusinessFailException("采购订单不存在");
        }
        stockOrderPurchase.setUpdateTime(new Date());
        stockOrderPurchaseMapper.updateByPrimaryKeySelective(stockOrderPurchase);
    }

    /**
     * 删除采购订单（逻辑删除）
     * @param stockOrderPurchase
     */
    @Transactional(rollbackFor = Exception.class)
    public void deletePurchase(StockOrderPurchase stockOrderPurchase) {
        StockOrderPurchase dbStockOrderPurchase = getPurchaseById(stockOrderPurchase.getOrderId());
        if (dbStockOrderPurchase == null) {
            throw new BusinessFailException("采购订单不存在");
        }
        dbStockOrderPurchase.setIsDelete(YesOrNoEnum.YES.getValue());
        dbStockOrderPurchase.setUpdateUserId(stockOrderPurchase.getUpdateUserId());
        dbStockOrderPurchase.setUpdateBy(stockOrderPurchase.getUpdateBy());
        dbStockOrderPurchase.setUpdateTime(new Date());
        stockOrderPurchaseMapper.updateByPrimaryKeySelective(dbStockOrderPurchase);
    }

    /**
     * 启用采购订单
     * @param stockOrderPurchase
     */
    @Transactional(rollbackFor = Exception.class)
    public void enablePurchase(StockOrderPurchase stockOrderPurchase) {
        StockOrderPurchase dbStockOrderPurchase = getPurchaseById(stockOrderPurchase.getOrderId());
        if (dbStockOrderPurchase == null) {
            throw new BusinessFailException("采购订单不存在");
        }
        if (YesOrNoEnum.YES.getValue().equals(dbStockOrderPurchase.getIsEnabled())) {
            return;
        }
        dbStockOrderPurchase.setIsEnabled(YesOrNoEnum.YES.getValue());
        dbStockOrderPurchase.setUpdateUserId(stockOrderPurchase.getUpdateUserId());
        dbStockOrderPurchase.setUpdateBy(stockOrderPurchase.getUpdateBy());
        dbStockOrderPurchase.setUpdateTime(new Date());
        stockOrderPurchaseMapper.updateByPrimaryKeySelective(dbStockOrderPurchase);
    }

    /**
     * 停用采购订单
     * @param stockOrderPurchase
     */
    @Transactional(rollbackFor = Exception.class)
    public void disablePurchase(StockOrderPurchase stockOrderPurchase) {
        StockOrderPurchase dbStockOrderPurchase = getPurchaseById(stockOrderPurchase.getOrderId());
        if (dbStockOrderPurchase == null) {
            throw new BusinessFailException("采购订单不存在");
        }
        if (YesOrNoEnum.NO.getValue().equals(dbStockOrderPurchase.getIsEnabled())) {
            return;
        }
        dbStockOrderPurchase.setIsEnabled(YesOrNoEnum.NO.getValue());
        dbStockOrderPurchase.setUpdateUserId(stockOrderPurchase.getUpdateUserId());
        dbStockOrderPurchase.setUpdateBy(stockOrderPurchase.getUpdateBy());
        dbStockOrderPurchase.setUpdateTime(new Date());
        stockOrderPurchaseMapper.updateByPrimaryKeySelective(dbStockOrderPurchase);
    }

    /**
     * 根据orderId分页查询采购订单明细列表
     * @param orderId 采购订单ID
     * @param pageNo 页码
     * @param pageSize 每页大小
     * @return
     */
    public List<StockOrderPurchaseDetail> getStockOrderPurchaseDetailListByParams(Long orderId, Integer pageNo, Integer pageSize) {
        StockOrderPurchaseDetailExample example = new StockOrderPurchaseDetailExample();
        StockOrderPurchaseDetailExample.Criteria criteria = example.createCriteria();

        if (orderId != null) {
            criteria.andOrderIdEqualTo(orderId);
        }
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());

        example.setOffset(PageUtils.getOffset(pageNo, pageSize));
        example.setLimit(pageSize);

        return stockOrderPurchaseDetailMapper.selectByExample(example);
    }

    /**
     * 添加采购订单明细
     * @param stockOrderPurchaseDetail
     */
    @Transactional(rollbackFor = Exception.class)
    public void addPurchaseDetail(StockOrderPurchaseDetail stockOrderPurchaseDetail) {
        validateStockOrderPurchaseDetail(stockOrderPurchaseDetail);
        stockOrderPurchaseDetail.setIsDelete(YesOrNoEnum.NO.getValue());
        stockOrderPurchaseDetail.setIsEnabled(YesOrNoEnum.YES.getValue());
        stockOrderPurchaseDetail.setCreateTime(new Date());
        stockOrderPurchaseDetailMapper.insertSelective(stockOrderPurchaseDetail);
    }

    /**
     * 校验采购订单明细实体
     * @param stockOrderPurchaseDetail
     */
    public void validateStockOrderPurchaseDetail(StockOrderPurchaseDetail stockOrderPurchaseDetail) {
        if (stockOrderPurchaseDetail.getOrderId() == null) {
            throw new BusinessFailException("采购订单ID不能为空");
        }
        // 根据业务可添加更多校验
    }

    /**
     * 根据ID查询采购订单明细
     * @param detailId
     * @return
     */
    public StockOrderPurchaseDetail getPurchaseDetailById(Long detailId) {
        if (detailId == null) {
            return null;
        }
        StockOrderPurchaseDetail stockOrderPurchaseDetail = stockOrderPurchaseDetailMapper.selectByPrimaryKey(detailId);
        if (stockOrderPurchaseDetail == null || YesOrNoEnum.YES.getValue().equals(stockOrderPurchaseDetail.getIsDelete())) {
            return null;
        }
        return stockOrderPurchaseDetail;
    }

    /**
     * 修改采购订单明细
     * @param stockOrderPurchaseDetail
     */
    @Transactional(rollbackFor = Exception.class)
    public void updatePurchaseDetail(StockOrderPurchaseDetail stockOrderPurchaseDetail) {
        validateStockOrderPurchaseDetail(stockOrderPurchaseDetail);
        StockOrderPurchaseDetail dbDetail = getPurchaseDetailById(stockOrderPurchaseDetail.getDetailId());
        if (dbDetail == null) {
            throw new BusinessFailException("采购订单明细不存在");
        }
        stockOrderPurchaseDetail.setUpdateTime(new Date());
        stockOrderPurchaseDetailMapper.updateByPrimaryKeySelective(stockOrderPurchaseDetail);
    }

    /**
     * 删除采购订单明细（逻辑删除）
     * @param stockOrderPurchaseDetail
     */
    @Transactional(rollbackFor = Exception.class)
    public void deletePurchaseDetail(StockOrderPurchaseDetail stockOrderPurchaseDetail) {
        StockOrderPurchaseDetail dbDetail = getPurchaseDetailById(stockOrderPurchaseDetail.getDetailId());
        if (dbDetail == null) {
            throw new BusinessFailException("采购订单明细不存在");
        }
        dbDetail.setIsDelete(YesOrNoEnum.YES.getValue());
        dbDetail.setUpdateUserId(stockOrderPurchaseDetail.getUpdateUserId());
        dbDetail.setUpdateBy(stockOrderPurchaseDetail.getUpdateBy());
        dbDetail.setUpdateTime(new Date());
        stockOrderPurchaseDetailMapper.updateByPrimaryKeySelective(dbDetail);
    }

    /**
     * 启用采购订单明细
     * @param stockOrderPurchaseDetail
     */
    @Transactional(rollbackFor = Exception.class)
    public void enablePurchaseDetail(StockOrderPurchaseDetail stockOrderPurchaseDetail) {
        StockOrderPurchaseDetail dbDetail = getPurchaseDetailById(stockOrderPurchaseDetail.getDetailId());
        if (dbDetail == null) {
            throw new BusinessFailException("采购订单明细不存在");
        }
        if (YesOrNoEnum.YES.getValue().equals(dbDetail.getIsEnabled())) {
            return;
        }
        dbDetail.setIsEnabled(YesOrNoEnum.YES.getValue());
        dbDetail.setUpdateUserId(stockOrderPurchaseDetail.getUpdateUserId());
        dbDetail.setUpdateBy(stockOrderPurchaseDetail.getUpdateBy());
        dbDetail.setUpdateTime(new Date());
        stockOrderPurchaseDetailMapper.updateByPrimaryKeySelective(dbDetail);
    }

    /**
     * 停用采购订单明细
     * @param stockOrderPurchaseDetail
     */
    @Transactional(rollbackFor = Exception.class)
    public void disablePurchaseDetail(StockOrderPurchaseDetail stockOrderPurchaseDetail) {
        StockOrderPurchaseDetail dbDetail = getPurchaseDetailById(stockOrderPurchaseDetail.getDetailId());
        if (dbDetail == null) {
            throw new BusinessFailException("采购订单明细不存在");
        }
        if (YesOrNoEnum.NO.getValue().equals(dbDetail.getIsEnabled())) {
            return;
        }
        dbDetail.setIsEnabled(YesOrNoEnum.NO.getValue());
        dbDetail.setUpdateUserId(stockOrderPurchaseDetail.getUpdateUserId());
        dbDetail.setUpdateBy(stockOrderPurchaseDetail.getUpdateBy());
        dbDetail.setUpdateTime(new Date());
        stockOrderPurchaseDetailMapper.updateByPrimaryKeySelective(dbDetail);
    }


    /**
     * 查询订单变动记录
     * @param clinicId
     * @param orderId
     * @param orderType
     * @param pageNo
     * @param pageSize
     * @return
     */
    public PageInfo<StockOrderLog> getLogListByCondition(Long clinicId,Long orderId,String orderType, Integer pageNo, Integer pageSize) {
        StockOrderLogExample example = new StockOrderLogExample();
        StockOrderLogExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        criteria.andOrderTypeEqualTo(orderType);
        criteria.andClinicIdEqualTo(clinicId);
        long totalCount = stockOrderLogMapper.countByExample(example);
        if(StringUtil.isBlank(totalCount)){
            return PageInfo.build();
        }
        example.setOffset(PageUtils.getOffset(pageNo, pageSize));
        example.setLimit(pageSize);
        example.setOrderByClause("create_time desc");
        List<StockOrderLog> logList = stockOrderLogMapper.selectByExample(example);
        return new PageInfo<>(totalCount,logList);
    }

    /**
     * 添加订单变动记录
     * @param orderId
     * @param orderType
     * @param logType
     * @param createUserId
     * @param createBy
     */
    @Transactional(rollbackFor = Exception.class)
    public void addOrderLog(Long clinicId, Long orderId, String orderType, String logType, Long createUserId, String createBy,String remark) {
        StockOrderLog stockOrderLog = new StockOrderLog();
        stockOrderLog.setClinicId(clinicId);
        stockOrderLog.setOrderId(orderId);
        stockOrderLog.setOrderType(orderType);
        stockOrderLog.setLogType(logType);
        stockOrderLog.setCreateUserId(createUserId);
        stockOrderLog.setCreateBy(createBy);
        stockOrderLog.setCreateTime(new Date());
        stockOrderLog.setRemark(remark);
        stockOrderLogMapper.insertSelective(stockOrderLog);
    }


    /**
     * 根据条件分页查询领用单列表
     * @param orderNo 单号
     * @param pageNo 页码
     * @param pageSize 每页大小
     * @return
     */
    public List<StockOrderReq> getStockOrderReqListByParams(String orderNo, Integer pageNo, Integer pageSize) {
        StockOrderReqExample example = new StockOrderReqExample();
        StockOrderReqExample.Criteria criteria = example.createCriteria();
        if (StringUtil.isNotBlank(orderNo)) {
            criteria.andOrderNoLike("%" + orderNo + "%");
        }
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        example.setOffset(PageUtils.getOffset(pageNo, pageSize));
        example.setLimit(pageSize);
        return stockOrderReqMapper.selectByExample(example);
    }

    /**
     * 添加领用单
     * @param stockOrderReq
     */
    @Transactional(rollbackFor = Exception.class)
    public void addReq(StockOrderReq stockOrderReq) {
        validateStockOrderReq(stockOrderReq);
        stockOrderReq.setIsDelete(YesOrNoEnum.NO.getValue());
        stockOrderReq.setIsEnabled(YesOrNoEnum.YES.getValue());
        stockOrderReq.setCreateTime(new Date());
        stockOrderReqMapper.insertSelective(stockOrderReq);
    }

    /**
     * 校验领用单实体
     * @param stockOrderReq
     */
    public void validateStockOrderReq(StockOrderReq stockOrderReq) {
        if (StringUtil.isBlank(stockOrderReq.getOrderNo())) {
            throw new BusinessFailException("单号不能为空");
        }
    }

    /**
     * 根据ID查询领用单
     * @param orderId
     * @return
     */
    public StockOrderReq getReqById(Long orderId) {
        if (StringUtil.isBlank(orderId)) {
            return null;
        }
        StockOrderReq stockOrderReq = stockOrderReqMapper.selectByPrimaryKey(orderId);
        if (stockOrderReq == null || YesOrNoEnum.YES.getValue().equals(stockOrderReq.getIsDelete())) {
            return null;
        }
        return stockOrderReq;
    }

    /**
     * 修改领用单
     * @param stockOrderReq
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateReq(StockOrderReq stockOrderReq) {
        validateStockOrderReq(stockOrderReq);
        StockOrderReq dbStockOrderReq = getReqById(stockOrderReq.getOrderId());
        if (dbStockOrderReq == null) {
            throw new BusinessFailException("领用单不存在");
        }
        stockOrderReq.setUpdateTime(new Date());
        stockOrderReqMapper.updateByPrimaryKeySelective(stockOrderReq);
    }

    /**
     * 删除领用单（逻辑删除）
     * @param stockOrderReq
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteReq(StockOrderReq stockOrderReq) {
        StockOrderReq dbStockOrderReq = getReqById(stockOrderReq.getOrderId());
        if (dbStockOrderReq == null) {
            throw new BusinessFailException("领用单不存在");
        }
        dbStockOrderReq.setIsDelete(YesOrNoEnum.YES.getValue());
        dbStockOrderReq.setUpdateUserId(stockOrderReq.getUpdateUserId());
        dbStockOrderReq.setUpdateBy(stockOrderReq.getUpdateBy());
        dbStockOrderReq.setUpdateTime(new Date());
        stockOrderReqMapper.updateByPrimaryKeySelective(dbStockOrderReq);
    }

    /**
     * 启用领用单
     * @param stockOrderReq
     */
    @Transactional(rollbackFor = Exception.class)
    public void enableReq(StockOrderReq stockOrderReq) {
        StockOrderReq dbStockOrderReq = getReqById(stockOrderReq.getOrderId());
        if (dbStockOrderReq == null) {
            throw new BusinessFailException("领用单不存在");
        }
        if (YesOrNoEnum.YES.getValue().equals(dbStockOrderReq.getIsEnabled())) {
            return;
        }
        dbStockOrderReq.setIsEnabled(YesOrNoEnum.YES.getValue());
        dbStockOrderReq.setUpdateUserId(stockOrderReq.getUpdateUserId());
        dbStockOrderReq.setUpdateBy(stockOrderReq.getUpdateBy());
        dbStockOrderReq.setUpdateTime(new Date());
        stockOrderReqMapper.updateByPrimaryKeySelective(dbStockOrderReq);
    }

    /**
     * 停用领用单
     * @param stockOrderReq
     */
    @Transactional(rollbackFor = Exception.class)
    public void disableReq(StockOrderReq stockOrderReq) {
        StockOrderReq dbStockOrderReq = getReqById(stockOrderReq.getOrderId());
        if (dbStockOrderReq == null) {
            throw new BusinessFailException("领用单不存在");
        }
        if (YesOrNoEnum.NO.getValue().equals(dbStockOrderReq.getIsEnabled())) {
            return;
        }
        dbStockOrderReq.setIsEnabled(YesOrNoEnum.NO.getValue());
        dbStockOrderReq.setUpdateUserId(stockOrderReq.getUpdateUserId());
        dbStockOrderReq.setUpdateBy(stockOrderReq.getUpdateBy());
        dbStockOrderReq.setUpdateTime(new Date());
        stockOrderReqMapper.updateByPrimaryKeySelective(dbStockOrderReq);
    }

    /**
     * 根据条件分页查询领用明细列表
     * @param orderId 单号
     * @param pageNo 页码
     * @param pageSize 每页大小
     * @return
     */
    public List<StockOrderReqDetail> getStockOrderReqDetailListByParams(Long orderId, Integer pageNo, Integer pageSize) {
        StockOrderReqDetailExample example = new StockOrderReqDetailExample();
        StockOrderReqDetailExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        example.setOffset(PageUtils.getOffset(pageNo, pageSize));
        example.setLimit(pageSize);
        return stockOrderReqDetailMapper.selectByExample(example);
    }

    /**
     * 添加领用明细
     * @param stockOrderReqDetail
     */
    @Transactional(rollbackFor = Exception.class)
    public void addReqDetail(StockOrderReqDetail stockOrderReqDetail) {
        validateStockOrderReqDetail(stockOrderReqDetail);
        stockOrderReqDetail.setIsDelete(YesOrNoEnum.NO.getValue());
        stockOrderReqDetail.setIsEnabled(YesOrNoEnum.YES.getValue());
        stockOrderReqDetail.setCreateTime(new Date());
        stockOrderReqDetailMapper.insertSelective(stockOrderReqDetail);
    }

    /**
     * 校验领用明细实体
     * @param stockOrderReqDetail
     */
    public void validateStockOrderReqDetail(StockOrderReqDetail stockOrderReqDetail) {

    }

    /**
     * 根据ID查询领用明细
     * @param detailId
     * @return
     */
    public StockOrderReqDetail getReqDetailById(Long detailId) {
        if (detailId == null) {
            return null;
        }
        StockOrderReqDetail stockOrderReqDetail = stockOrderReqDetailMapper.selectByPrimaryKey(detailId);
        if (stockOrderReqDetail == null || YesOrNoEnum.YES.getValue().equals(stockOrderReqDetail.getIsDelete())) {
            return null;
        }
        return stockOrderReqDetail;
    }

    /**
     * 修改领用明细
     * @param stockOrderReqDetail
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateReqDetail(StockOrderReqDetail stockOrderReqDetail) {
        validateStockOrderReqDetail(stockOrderReqDetail);
        StockOrderReqDetail dbStockOrderReqDetail = getReqDetailById(stockOrderReqDetail.getDetailId());
        if (dbStockOrderReqDetail == null) {
            throw new BusinessFailException("领用明细不存在");
        }
        stockOrderReqDetail.setUpdateTime(new Date());
        stockOrderReqDetailMapper.updateByPrimaryKeySelective(stockOrderReqDetail);
    }

    /**
     * 删除领用明细（逻辑删除）
     * @param stockOrderReqDetail
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteReqDetail(StockOrderReqDetail stockOrderReqDetail) {
        StockOrderReqDetail dbStockOrderReqDetail = getReqDetailById(stockOrderReqDetail.getDetailId());
        if (dbStockOrderReqDetail == null) {
            throw new BusinessFailException("领用明细不存在");
        }
        dbStockOrderReqDetail.setIsDelete(YesOrNoEnum.YES.getValue());
        dbStockOrderReqDetail.setUpdateUserId(stockOrderReqDetail.getUpdateUserId());
        dbStockOrderReqDetail.setUpdateBy(stockOrderReqDetail.getUpdateBy());
        dbStockOrderReqDetail.setUpdateTime(new Date());
        stockOrderReqDetailMapper.updateByPrimaryKeySelective(dbStockOrderReqDetail);
    }

    /**
     * 启用领用明细
     * @param stockOrderReqDetail
     */
    @Transactional(rollbackFor = Exception.class)
    public void enableReqDetail(StockOrderReqDetail stockOrderReqDetail) {
        StockOrderReqDetail dbStockOrderReqDetail = getReqDetailById(stockOrderReqDetail.getDetailId());
        if (dbStockOrderReqDetail == null) {
            throw new BusinessFailException("领用明细不存在");
        }
        if (YesOrNoEnum.YES.getValue().equals(dbStockOrderReqDetail.getIsEnabled())) {
            return;
        }
        dbStockOrderReqDetail.setIsEnabled(YesOrNoEnum.YES.getValue());
        dbStockOrderReqDetail.setUpdateUserId(stockOrderReqDetail.getUpdateUserId());
        dbStockOrderReqDetail.setUpdateBy(stockOrderReqDetail.getUpdateBy());
        dbStockOrderReqDetail.setUpdateTime(new Date());
        stockOrderReqDetailMapper.updateByPrimaryKeySelective(dbStockOrderReqDetail);
    }

    /**
     * 停用领用明细
     * @param stockOrderReqDetail
     */
    @Transactional(rollbackFor = Exception.class)
    public void disableReqDetail(StockOrderReqDetail stockOrderReqDetail) {
        StockOrderReqDetail dbStockOrderReqDetail = getReqDetailById(stockOrderReqDetail.getDetailId());
        if (dbStockOrderReqDetail == null) {
            throw new BusinessFailException("领用明细不存在");
        }
        if (YesOrNoEnum.NO.getValue().equals(dbStockOrderReqDetail.getIsEnabled())) {
            return;
        }
        dbStockOrderReqDetail.setIsEnabled(YesOrNoEnum.NO.getValue());
        dbStockOrderReqDetail.setUpdateUserId(stockOrderReqDetail.getUpdateUserId());
        dbStockOrderReqDetail.setUpdateBy(stockOrderReqDetail.getUpdateBy());
        dbStockOrderReqDetail.setUpdateTime(new Date());
        stockOrderReqDetailMapper.updateByPrimaryKeySelective(dbStockOrderReqDetail);
    }

    /**
     * 根据条件分页查询调拨单列表
     * @param orderNo 单号
     * @param pageNo 页码
     * @param pageSize 每页大小
     * @return
     */
    public List<StockOrderTransfer> getStockOrderTransferListByParams(String orderNo, Integer pageNo, Integer pageSize) {
        StockOrderTransferExample example = new StockOrderTransferExample();
        StockOrderTransferExample.Criteria criteria = example.createCriteria();
        if (StringUtil.isNotBlank(orderNo)) {
            criteria.andOrderNoLike("%" + orderNo + "%");
        }
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        example.setOffset(PageUtils.getOffset(pageNo, pageSize));
        example.setLimit(pageSize);
        return stockOrderTransferMapper.selectByExample(example);
    }

    /**
     * 添加调拨单
     * @param stockOrderTransfer
     */
    @Transactional(rollbackFor = Exception.class)
    public void addTransfer(StockOrderTransfer stockOrderTransfer) {
        validateStockOrderTransfer(stockOrderTransfer);
        stockOrderTransfer.setIsDelete(YesOrNoEnum.NO.getValue());
        stockOrderTransfer.setIsEnabled(YesOrNoEnum.YES.getValue());
        stockOrderTransfer.setCreateTime(new Date());
        stockOrderTransferMapper.insertSelective(stockOrderTransfer);
    }

    /**
     * 校验调拨单实体
     * @param stockOrderTransfer
     */
    public void validateStockOrderTransfer(StockOrderTransfer stockOrderTransfer) {
        if (StringUtil.isBlank(stockOrderTransfer.getOrderNo())) {
            throw new BusinessFailException("单号不能为空");
        }
    }

    /**
     * 根据ID查询调拨单
     * @param orderId
     * @return
     */
    public StockOrderTransfer getTransferById(Long orderId) {
        if (orderId == null) {
            return null;
        }
        StockOrderTransfer stockOrderTransfer = stockOrderTransferMapper.selectByPrimaryKey(orderId);
        if (stockOrderTransfer == null || YesOrNoEnum.YES.getValue().equals(stockOrderTransfer.getIsDelete())) {
            return null;
        }
        return stockOrderTransfer;
    }

    /**
     * 修改调拨单
     * @param stockOrderTransfer
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateTransfer(StockOrderTransfer stockOrderTransfer) {
        validateStockOrderTransfer(stockOrderTransfer);
        StockOrderTransfer transfer = getTransferById(stockOrderTransfer.getOrderId());
        if (transfer == null) {
            throw new BusinessFailException("调拨单不存在");
        }
        stockOrderTransfer.setUpdateTime(new Date());
        stockOrderTransferMapper.updateByPrimaryKeySelective(stockOrderTransfer);
    }

    /**
     * 删除调拨单（逻辑删除）
     * @param stockOrderTransfer
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteTransfer(StockOrderTransfer stockOrderTransfer) {
        StockOrderTransfer transfer = getTransferById(stockOrderTransfer.getOrderId());
        if (transfer == null) {
            throw new BusinessFailException("调拨单不存在");
        }
        transfer.setIsDelete(YesOrNoEnum.YES.getValue());
        transfer.setUpdateUserId(stockOrderTransfer.getUpdateUserId());
        transfer.setUpdateBy(stockOrderTransfer.getUpdateBy());
        transfer.setUpdateTime(new Date());
        stockOrderTransferMapper.updateByPrimaryKeySelective(transfer);
    }

    /**
     * 启用调拨单
     * @param stockOrderTransfer
     */
    @Transactional(rollbackFor = Exception.class)
    public void enableTransfer(StockOrderTransfer stockOrderTransfer) {
        StockOrderTransfer transfer = getTransferById(stockOrderTransfer.getOrderId());
        if (transfer == null) {
            throw new BusinessFailException("调拨单不存在");
        }
        if (YesOrNoEnum.YES.getValue().equals(transfer.getIsEnabled())) {
            return;
        }
        transfer.setIsEnabled(YesOrNoEnum.YES.getValue());
        transfer.setUpdateUserId(stockOrderTransfer.getUpdateUserId());
        transfer.setUpdateBy(stockOrderTransfer.getUpdateBy());
        transfer.setUpdateTime(new Date());
        stockOrderTransferMapper.updateByPrimaryKeySelective(transfer);
    }

    /**
     * 停用调拨单
     * @param stockOrderTransfer
     */
    @Transactional(rollbackFor = Exception.class)
    public void disableTransfer(StockOrderTransfer stockOrderTransfer) {
        StockOrderTransfer transfer = getTransferById(stockOrderTransfer.getOrderId());
        if (transfer == null) {
            throw new BusinessFailException("调拨单不存在");
        }
        if (YesOrNoEnum.NO.getValue().equals(transfer.getIsEnabled())) {
            return;
        }
        transfer.setIsEnabled(YesOrNoEnum.NO.getValue());
        transfer.setUpdateUserId(stockOrderTransfer.getUpdateUserId());
        transfer.setUpdateBy(stockOrderTransfer.getUpdateBy());
        transfer.setUpdateTime(new Date());
        stockOrderTransferMapper.updateByPrimaryKeySelective(transfer);
    }

    /**
     * 根据条件分页查询调拨明细列表
     * @param orderId 单号
     * @param pageNo 页码
     * @param pageSize 每页大小
     * @return
     */
    public List<StockOrderTransferDetail> getStockOrderTransferDetailListByParams(Long orderId, Integer pageNo, Integer pageSize) {
        StockOrderTransferDetailExample example = new StockOrderTransferDetailExample();
        StockOrderTransferDetailExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        example.setOffset(PageUtils.getOffset(pageNo, pageSize));
        example.setLimit(pageSize);
        return stockOrderTransferDetailMapper.selectByExample(example);
    }

    /**
     * 添加调拨明细
     * @param stockOrderTransferDetail
     */
    @Transactional(rollbackFor = Exception.class)
    public void addTransferDetail(StockOrderTransferDetail stockOrderTransferDetail) {
        validateStockOrderTransferDetail(stockOrderTransferDetail);
        stockOrderTransferDetail.setIsDelete(YesOrNoEnum.NO.getValue());
        stockOrderTransferDetail.setIsEnabled(YesOrNoEnum.YES.getValue());
        stockOrderTransferDetail.setCreateTime(new Date());
        stockOrderTransferDetailMapper.insertSelective(stockOrderTransferDetail);
    }

    /**
     * 校验调拨明细实体
     * @param stockOrderTransferDetail
     */
    public void validateStockOrderTransferDetail(StockOrderTransferDetail stockOrderTransferDetail) {

    }

    /**
     * 根据ID查询调拨明细
     * @param detailId
     * @return
     */
    public StockOrderTransferDetail getTransferDetailById(Long detailId) {
        if (detailId == null) {
            return null;
        }
        StockOrderTransferDetail detail = stockOrderTransferDetailMapper.selectByPrimaryKey(detailId);
        if (detail == null || YesOrNoEnum.YES.getValue().equals(detail.getIsDelete())) {
            return null;
        }
        return detail;
    }

    /**
     * 修改调拨明细
     * @param stockOrderTransferDetail
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateTransferDetail(StockOrderTransferDetail stockOrderTransferDetail) {
        validateStockOrderTransferDetail(stockOrderTransferDetail);
        StockOrderTransferDetail detail = getTransferDetailById(stockOrderTransferDetail.getDetailId());
        if (detail == null) {
            throw new BusinessFailException("调拨明细不存在");
        }
        stockOrderTransferDetail.setUpdateTime(new Date());
        stockOrderTransferDetailMapper.updateByPrimaryKeySelective(stockOrderTransferDetail);
    }

    /**
     * 删除调拨明细（逻辑删除）
     * @param stockOrderTransferDetail
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteTransferDetail(StockOrderTransferDetail stockOrderTransferDetail) {
        StockOrderTransferDetail detail = getTransferDetailById(stockOrderTransferDetail.getDetailId());
        if (detail == null) {
            throw new BusinessFailException("调拨明细不存在");
        }
        detail.setIsDelete(YesOrNoEnum.YES.getValue());
        detail.setUpdateUserId(stockOrderTransferDetail.getUpdateUserId());
        detail.setUpdateBy(stockOrderTransferDetail.getUpdateBy());
        detail.setUpdateTime(new Date());
        stockOrderTransferDetailMapper.updateByPrimaryKeySelective(detail);
    }

    /**
     * 启用调拨明细
     * @param stockOrderTransferDetail
     */
    @Transactional(rollbackFor = Exception.class)
    public void enableTransferDetail(StockOrderTransferDetail stockOrderTransferDetail) {
        StockOrderTransferDetail detail = getTransferDetailById(stockOrderTransferDetail.getDetailId());
        if (detail == null) {
            throw new BusinessFailException("调拨明细不存在");
        }
        if (YesOrNoEnum.YES.getValue().equals(detail.getIsEnabled())) {
            return;
        }
        detail.setIsEnabled(YesOrNoEnum.YES.getValue());
        detail.setUpdateUserId(stockOrderTransferDetail.getUpdateUserId());
        detail.setUpdateBy(stockOrderTransferDetail.getUpdateBy());
        detail.setUpdateTime(new Date());
        stockOrderTransferDetailMapper.updateByPrimaryKeySelective(detail);
    }

    /**
     * 停用调拨明细
     * @param stockOrderTransferDetail
     */
    @Transactional(rollbackFor = Exception.class)
    public void disableTransferDetail(StockOrderTransferDetail stockOrderTransferDetail) {
        StockOrderTransferDetail detail = getTransferDetailById(stockOrderTransferDetail.getDetailId());
        if (detail == null) {
            throw new BusinessFailException("调拨明细不存在");
        }
        if (YesOrNoEnum.NO.getValue().equals(detail.getIsEnabled())) {
            return;
        }
        detail.setIsEnabled(YesOrNoEnum.NO.getValue());
        detail.setUpdateUserId(stockOrderTransferDetail.getUpdateUserId());
        detail.setUpdateBy(stockOrderTransferDetail.getUpdateBy());
        detail.setUpdateTime(new Date());
        stockOrderTransferDetailMapper.updateByPrimaryKeySelective(detail);
    }

}
